package crons

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
	"hotgo/internal/consts"
	"hotgo/internal/dao"
	"hotgo/internal/library/cron"
	"hotgo/internal/model/entity"
	"hotgo/internal/service"
	"time"
)

func init() {
	cron.Register(AuctionStart)
}

var AuctionStart = &cAuctionStart{name: "auction_start"}

type cAuctionStart struct {
	name string
}

func (c *cAuctionStart) GetName() string {
	return c.name
}

// Execute 执行任务
func (c *cAuctionStart) Execute(ctx context.Context, parser *cron.Parser) (err error) {
	// 业务逻辑
	var (
		mapperList []entity.AuctionProductMapper
	)
	// 查询可用竞拍活动
	if err = service.SysAuctionProductMapper().Model(ctx).
		Where(dao.AuctionProductMapper.Columns().Status, consts.AuctionStatusWaitStart).
		WhereLTE(dao.AuctionProductMapper.Columns().StartTime, gtime.Now()).
		Scan(&mapperList); err != nil {
		parser.Logger.Warning(ctx, "cron AuctionEnd Execute err: ", err)
		return
	}
	for _, mapper := range mapperList {
		if _, err = service.SysAuctionProductMapper().Model(ctx).
			WherePri(mapper.Id).
			Data(g.Map{
				dao.AuctionProductMapper.Columns().Status: consts.AuctionStatusWorking,
			}).Update(); err != nil {
			parser.Logger.Warning(ctx, "cron AuctionEnd Execute err: ", err)
			continue
		}
	}

	var logList []entity.AuctionLog
	if err = service.SysAuctionLog().Model(ctx).
		Where(dao.AuctionLog.Columns().Status, consts.AuctionLogWaitStart).
		Wheref("(start_time <= ? AND date = ?) OR date < ?", time.Now().Format(time.TimeOnly), time.Now().Format(time.DateOnly), time.Now().Format(time.DateOnly)).
		//WhereGTE(dao.AuctionLog.Columns().EndTime, time.Now().Format(time.TimeOnly)).
		Scan(&logList); err != nil {
		parser.Logger.Warning(ctx, "cron AuctionEnd Execute err: ", err)
		return
	}

	for _, log := range logList {
		if _, err = service.SysAuctionLog().Model(ctx).
			WherePri(log.Id).
			Data(g.Map{
				dao.AuctionLog.Columns().Status: consts.AuctionLogWorking,
			}).Update(); err != nil {
			parser.Logger.Warning(ctx, "cron AuctionEnd Execute err: ", err)
			continue
		}
	}

	return
}
